package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Config;
import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;

public class DefaultHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        // TODO: [222024321072052/然娜·吐尔逊汗]
        String requestUrl = request.getUrl();
        String fileName = requestUrl.equals("/") ? "index.html" : requestUrl.substring(1);
        Path filePath = Paths.get(Config.getInstance().getWebRoot(), fileName).toAbsolutePath().normalize();
        Path webRootPath = Paths.get(Config.getInstance().getWebRoot()).toAbsolutePath().normalize();

        // 防止路径穿越攻击
        if (!filePath.startsWith(webRootPath)) {
            sendErrorResponse(response, 403, "Forbidden: Invalid path");
            return;
        }

        try {
            if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
                byte[] fileBytes = Files.readAllBytes(filePath);
                // TODO: [222024321072052/然娜·吐尔逊汗] 确定并设置正确的 Content-Type (例如 text/html, image/jpeg 等)
                String contentType = Files.probeContentType(filePath);
                if (contentType == null) {
                    contentType = "application/octet-stream";
                }

                // 200 OK响应
                response.write(("HTTP/1.1 200 OK\r\n").getBytes(StandardCharsets.UTF_8));
                response.write(("Content-Type: " + contentType + "\r\n").getBytes(StandardCharsets.UTF_8));
                response.write(("Content-Length: " + fileBytes.length + "\r\n").getBytes(StandardCharsets.UTF_8));
                response.write(("Connection: close\r\n").getBytes(StandardCharsets.UTF_8));
                response.write(("\r\n").getBytes(StandardCharsets.UTF_8));
                response.write(fileBytes);
            } else {
                // 404 Not Found
                sendErrorResponse(response, 404, "Not Found: " + requestUrl);
            }
        } catch (IOException e) {
            // 已实现500错误响应 - 学号：222024321072052/姓名：然娜·吐尔逊汗
            sendErrorResponse(response, 500, "Internal Server Error: " + e.getMessage());
        } finally {
            try {
                response.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void sendErrorResponse(OutputStream response, int statusCode, String message) {
        try {
            String statusText = switch (statusCode) {
                case 403 -> "Forbidden";
                case 404 -> "Not Found";
                case 500 -> "Internal Server Error";
                default -> "Unknown Error";
            };
            String content = String.format(
                    "<h1>%d %s</h1><p>%s</p>",
                    statusCode, statusText, message
            );
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);

            response.write(("HTTP/1.1 " + statusCode + " " + statusText + "\r\n").getBytes(StandardCharsets.UTF_8));
            response.write(("Content-Type: text/html; charset=UTF-8\r\n").getBytes(StandardCharsets.UTF_8));
            response.write(("Content-Length: " + contentBytes.length + "\r\n").getBytes(StandardCharsets.UTF_8));
            response.write(("Connection: close\r\n").getBytes(StandardCharsets.UTF_8));
            response.write(("\r\n").getBytes(StandardCharsets.UTF_8));
            response.write(contentBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}